package Lee_code;

import java.util.Deque;
import java.util.LinkedList;
import java.util.stream.Collectors;

/**
 * @author blh
 * @date 2024年07月07日 22:29
 */
public class Lee_402_77 {
    public String removeKdigits(String num, int k) {
        int len = num.length();
        if (len <= k) {
            return "0";
        }
        Deque<Character> deque = new LinkedList<>();
        int i = 0;

        while (i < len) {
            if (deque.isEmpty()) {
                deque.push(num.charAt(i));
            } else if (num.charAt(i) < deque.peek() && k > 0) {
                deque.pop();
                deque.push(num.charAt(i));
                i--;
                k--;
            } else if (num.charAt(i) > deque.peek() && k > 0) {
                deque.push(num.charAt(i));
            } else if (num.charAt(i) == deque.peek()) {
                deque.push(num.charAt(i));
            } else if (k == 0) {
                deque.push(num.charAt(i));
            }
            i++;
        }
        StringBuilder sb = new StringBuilder();
        while (k != 0) {
            k--;
            deque.removeFirst();
        }

        int n = deque.size();
        for (int j = 0; j < n; j++) {
            sb.append(deque.pollLast());
        }
        int sign = 0;
        for (int j = 0; j < sb.length(); j++) {
            if (sb.charAt(j) != '0') {
                sign = j;
                break;
            }
        }
        if (Integer.parseInt(sb.toString()) == 0) {
            return "0";
        }
        return sb.substring(sign);
    }
}
